const roleService = require("../service/roleService")
const {dataHandler} = require('../utils/handle-data')
class RoleController {
  async createRole(ctx, next) {
    const { roleName, roleDesc } = ctx.request.body 
    const res = await roleService.createRole(roleName, roleDesc)
    const id = res.insertId
    const data = await roleService.getRoleById(id)
    ctx.body = {
      data,
      meta: {
        msg: '创建成功',
        status:201
      }
    }
  }
  async getRoleById(ctx, next) {
    const { id } = ctx.params 
    console.log(id);
    const res = await roleService.getRoleById(id)
    ctx.body = {
      data: res,
      meta: {
        msg: '获取成功',
        status:200
      }
    }
  }
  async updateRole(ctx, next) {
    const { id } = ctx.params
    const {roleName,roleDesc} = ctx.request.body
    await roleService.updateRole(id, roleName, roleDesc)
    const data = await roleService.getRoleById(id)

    ctx.body = {
      data,
      meta: {
        msg: '修改成功',
        status:200
      }
    }
  }
  async removeRoleById(ctx, next) {
    const { id } = ctx.params
    const res = await roleService.removeRoleById(id)
    console.log(res);
    if (res.affectedRows === 1) {
      ctx.body = {
        data: null,
        meta: {
          msg: '删除成功',
          status:200
        }
      }
    } else {
      ctx.body = {
        data: null,
        meta: {
          msg: '删除失败',
          status:400
        }
      }
    }
    
  }
  async giveRights(ctx, next) {
    const { roleId } = ctx.params
    const { rids } = ctx.request.body
    
    await roleService.giveRights(roleId, rids)
    ctx.body = {
      data: null,
      meta: {
        msg: '更新成功',
        status:200
      }
    }
  }
  async getRoleList(ctx, next) {
    const res = await roleService.getRoleList()
    res.forEach(item => {
      console.log(item.children);
      item.children = dataHandler(item.children, 'tree')

    })
    ctx.body = {
      data:res,
      meta: {
        msg: '获取成功',
        status:200
      }
    }
  }
  async removeRight(ctx, next) {
    const { roleId, rightId } = ctx.params
    const res = await roleService.removeRight(roleId, rightId)
    if (res.affectedRows === 1) {
      const data = await roleService.getRoleListById(roleId)
      console.log(data);
      data[0].children = dataHandler(data[0].children, 'tree')
      ctx.body = {
        data,
        meta: {
          msg: '删除成功',
          status:200
        }
      }
    } else {
      ctx.body = {
        data: null,
        meta: {
          msg: '删除失败',
          status:400
        }
      }
    }
  }
}
module.exports = new RoleController()